package tw.com.diray.set;

import tw.com.diary.ae.com.DirayBussinessException;
import tw.com.diary.ae.com.Msg;
import tw.com.diary.api.domain.ModifyPasswordDTO;
import tw.com.diary.api.service.ModifyPasswordService;
import tw.com.diary.core.ModifyPasswordServiceImpl;
import tw.com.diray.R;
import tw.com.diray.comm.ui.DirToast;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

public class ModfiyPassswordFragment extends Fragment {

	private ModifyPasswordDTO dto = null;
	private ModifyPasswordService service;

	private EditText oldPassword;//舊密碼畫面元件
	private EditText newPassowrd;//新密碼
	private EditText newPassowrd1;//另一個新密碼

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setHasOptionsMenu(true);

		this.dto = new ModifyPasswordDTO();
		this.service = ModifyPasswordServiceImpl.intance(this.getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.activity_modify_password, container, false);

		this.oldPassword = (EditText) rootView.findViewById(R.id.oldText);
		this.newPassowrd = (EditText) rootView.findViewById(R.id.newText);
		this.newPassowrd1 = (EditText) rootView.findViewById(R.id.newPassword2);

		return rootView;

	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub

		inflater.inflate(R.menu.modify_password, menu);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		final int id = item.getItemId();

		switch (id) {
		case R.id.action_sumit:

			try {

				if (TextUtils.isEmpty(this.oldPassword.getText().toString())) {
					throw new DirayBussinessException(Msg.W0001,"舊密碼");
				}
				
				if (TextUtils.isEmpty(this.newPassowrd.getText().toString())) {
					throw new DirayBussinessException(Msg.W0001,"第一組密碼");
				}
				if (TextUtils.isEmpty(this.newPassowrd1.getText().toString())) {
					throw new DirayBussinessException(Msg.W0001,"第二組密碼");
				}
				

				this.dto.setNewPassword(this.newPassowrd.getText().toString());
				this.dto.setNewPassword2(this.newPassowrd1.getText().toString());
				this.dto.setOldPassword(this.oldPassword.getText().toString());

				this.service.modifyPassword(dto);// 修改密碼
				DirToast.show(getActivity(), Msg.S0001, "密碼已修改");
			} catch (Exception e) {
				DirToast.show(getActivity(), e);
			}
			break;

		default:

			break;
		}

		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}
}
